package be.tf.freemaind.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.tf.freemaind.dao.UserDao;
import be.tf.freemaind.exceptions.FreeMaindException;
import be.tf.freemaind.model.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/doLogin")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		ServletContext context=this.getServletContext();
		Statement stm=(Statement)context.getAttribute("stm");
		String error=null;
		
		User user=new User();
		user.setName((String)request.getParameter("name"));
		user.setPassword((String)request.getParameter("password"));
		
		
		UserDao userDao=new UserDao(stm);
		try {
			// check in the db 
			boolean isLogged=userDao.login(user);
			
			if (isLogged) {
				// get the right user object with the username that match from the db
				user = userDao.findByUserName(user.getName());
				
				// record the user in the session
				HttpSession session = request.getSession();
				session.setAttribute("userLogged",user);
				
				
				// redirect to the home page and exit
				System.out.println("logged user "+ user.getName());
				System.out.println("logged user "+ String.valueOf(user.getRole()));
				
				
				response.sendRedirect(request.getContextPath());
				//request.getRequestDispatcher("/index").forward(request,response);
				return;
				
			}else{
				error="Bad password";
			}
		} catch (FreeMaindException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			error=e.getMessage();
		}
		request.setAttribute("error", error);
		response.sendRedirect(request.getContextPath());
		//request.getRequestDispatcher("/jsp/Login.jsp").forward(request,response);
		
	}

}
